<?php
class TweetsController extends AppController{
	public $components = array ('Session');
	public $helper = array ('Html'=>'Form');
	public $userId =1;
	public $uses = array('User','Timeline','Tweet','Place','Favorite','Mention','Follow');
	public function beforeFilter() {
		parent::beforeFilter();
		$mobile = preg_match('/android/i',$_SERVER['HTTP_USER_AGENT']);
		//debug($_SERVER['HTTP_USER_AGENT']);
		//debug($mobile);
		if($mobile){
			$this->autoRender =false;
		}
		else{
			$this->autoRender = true;
		}
	}


	public  function index(){
		//$this->set($this->data,$this->Tweet);
		echo $_SERVER['HTTP_USER_AGENT'];
		//$this->redirect(array('controller'=>'tweets','action'=>'add'));
	}
	public function update(){
		//$this->autoRender = false;

		$err = null;
		$response;
		if($this->request->is('post')){
			if(empty($this->request->data['content'])){
				$err .= "not found content param";

			}
			if(!isset($this->request->data['user_id'])){
				$err .= "not found user_id param";
					
			}

			if(!isset($this->request->data['image_url'])){
				$err .= "not found image_id param";

			}
			if(empty($this->request->data['parent_id'])){
				$err .= "not found parent_id param";
					
			}
			if(empty($this->request->data['type'])){
				$err .= "not found type param";
					
			}
			if(empty($this->request->data['place_id'])){
				$err .= "not found place_id param";
					
			}
			//debug($this->request->data);
			//debug(empty($err));
			if(empty($err)){

				$content = $this->request->data['content'];
				$imageUrl = $this->request->data['image_url'];

				$userId = $this->request->data['user_id'];
				$parentId = $this->request->data['parent_id'];
				$type= $this->request->data['type'];
				$placeId = $this->request->data['place_id'];
				if($this->insertTweet($userId, $content, $imageUrl, $parentId, $type,$placeId)<0){
					$response = array("status_code" => -1,"message" => "Tweet fail!!!","entity" => array());
				}
				else{
					$response = array("status_code" => 0,"message" => "Tweet ok!!!","entity" => array());
				}


			}
			else {
				$response = array("status_code" => -1,"message" => $err,"entity" =>'');
			}
			echo json_encode($response);

		}
		//$this->redirect("http://faketwitter.com/tweets");
	}

	public function update_with_media(){
		//$this->autoRender = false;
		$dataSource = $this->Tweet->getDataSource();
		$err = null;
		$response;
		if($this->request->is('post')){
			if(empty($this->request->data['content'])){
				$err .= "not found content param";

			}
			if(!isset($this->request->data['image_url'])){
				$err .= "not found image_id param";

			}
			if(empty($this->request->data['parent_id'])){
				$err .= "not found parent_id param";
					
			}
			if(empty($this->request->data['type'])){
				$err .= "not found type param";
					
			}
			if(empty($_FILES["media"])){
				$err.= "not found media param";
			}
			if(empty($this->request->data['place_id'])){
				$err .= "not found place_id param";
					
			}
			//debug(empty($err));
			if(empty($err)){
				$folderPath =  WWW_ROOT.str_replace('/', DS, IMAGE_TWEET);

				if (!is_dir($folderPath)) {
					$this->Folder = new Folder();
					$flg = $this->Folder->create($folderPath, 0777);
					if (!$flg) {
						return 'Have error when create folder';
					};
				};
				$name='';
				if (!empty($_FILES['media'])) {
					$fileName = time().$_FILES['media']['name'];
					$uploadFile = $folderPath . basename($fileName);
					move_uploaded_file($_FILES['media']['tmp_name'], $uploadFile);
					$name= $fileName;
					//debug($name);
				}
				//debug($_SERVER['SERVER_ADDR']);
				$preUrl = IMAGE_TWEET;
				$content = $this->request->data['content'];
				$imageUrl = $preUrl.$name;

				$userId = $this->request->data['user_id'];
				$parentId = $this->request->data['parent_id'];
				$type= $this->request->data['type'];
				$placeId = $this->request->data['place_id'];

				if($this->insertTweet($userId, $content, $imageUrl, $parentId, $type,$placeId)<0){
					$response = array("status_code" => -1,"message" => "Tweet fail!!!","entity" => array());
				}
				else{
					$response = array("status_code" => 0,"message" => "Tweet ok!!!","entity" => array());
				}
					
			}
			else {
				$response = array("status_code" => -1,"message" => $err,"entity" =>'');
			}
			echo json_encode($response);

		}
		//$this->redirect("http://faketwitter.com/tweets");
	}

	public function retweet(){
		//$this->autoRender = true;

		$err = null;
		$response;
		if($this->request->is('post')){
			//$this->autoRender = false;
			if(empty($this->request->data['tweet_id'])){
				$err .= "not found tweet_id param";

			}
			if(!isset($this->request->data['user_id'])){
				$err .= "not found user_id param";
					
			}
			//debug($this->request->data);
			//debug(empty($err));
			if(empty($err)){
				//check da retweet chua

				$content = '';
				$imageUrl = '';

				$userId = $this->request->data['user_id'];
				$parentId = $this->request->data['tweet_id'];
				$type= 3;
				$retweet = $this->Tweet->find('first',
						array('conditions'=>array('Tweet.user_id'=>$userId,'Tweet.parent_id'=>$parentId,'Tweet.type'=>3),'recursive'=>-1));

				if($retweet==null){
					if($this->insertReTweet($userId, $content, $imageUrl, $parentId, $type)<0){
						$response = array("status_code" => -1,"message" => "ReTweet fail!!!","entity" => array());
					}
					else{
						$response = array("status_code" => 0,"message" => "ReTweet ok!!!","entity" => array());
					}
				}
				else{
					$response = array("status_code" => -1,"message" => "You have retweeted this tweet!!!","entity" => array());
				}
			}
			else {
				$response = array("status_code" => -1,"message" => $err,"entity" =>'');
			}
			echo json_encode($response);

		}

	}
	private  function checkFollowerStatus($userid,$followers){
		$followings = $this->Follow->find("all" , array("conditions" => array("follower_id" => $userid),
				"fields" => array("FollowerUser.id"),"order" => array('id' => 'asc')));

		for($i = 0;$i < count($followers);$i++){
			for($j = 0;$j < count($followings) ; $j++){
				if($followers[$i]["FollowingUser"]["id"] == $followings[$j]["FollowerUser"]["id"]){
					$followers[$i]["FollowingUser"]["followStatus"] = true;
					break;
				}
			}
			if(!isset($followers[$i]["FollowingUser"]["followStatus"])){
				$followers[$i]["FollowingUser"]["followStatus"] = false;
			}
		}
		return  $followers;
	}
	public function listretweeteduser(){
		$err = null;
		$response;
		if($this->request->is('post')){
			if(empty($this->request->data['tweet_id'])){
				$err .= "not found tweet_id param";

			}
			if(empty($this->request->data['page'])){
				$err .= "not found page param";
					
			}
			if(empty($this->request->data['count'])){
				$err .= "not found count param";
					
			}

			//debug($this->request->data);
			//debug(empty($err));
			if(empty($err)){
				//check da retweet chua

				$userId = $this->request->data['userid'];
				$parentId = $this->request->data['tweet_id'];
				$page	= $this->request->data['page'];
				$count = $this->request->data['count'];
				$type= 3;
				$this->Tweet->unbindModel(array('hasMany'=>array('Timeline','Mention','Favorite'),'hasOne'=>array('Place')));



				if($page>0){
					$listuser= $this->Tweet->find('all',array('conditions'=>array('Tweet.parent_id'=>$parentId,'Tweet.type'=>$type),
							'limit'=> $count,
							'offset'=>$count*($page-1),
							'fields'=>array('User.id','User.username','User.email','User.avatar','User.screen_name'),
							'order by User.id DESC'));
				}
				else{
					$listuser= $this->Tweet->find('all',array('conditions'=>array('Tweet.parent_id'=>$parentId,'Tweet.type'=>$type),

							'fields'=>array('User.id','User.username','User.email','User.avatar','User.screen_name','User.created'),
							'order by User.id DESC'));
				}
				$followings = $this->Follow->find("all" , array("conditions" => array("follower_id" => $userId),
						"fields" => array("Follow.following_id"),'recursive'=>-1));
				//debug($followings);
				foreach ($listuser as $key =>$value){
					//debug($value);
					$check = 0;
					foreach ($followings as $key1 =>$value1){
						//debug($value1);

						if($value['User']['id']==$value1['Follow']['following_id']){
							$listuser[$key]['User']['followStatus']=true;
							$check =1;
							break;
						}

					}
					if(!$check){
						$listuser[$key]['User']['followStatus']=false;
					}
				}
				//debug($listuser);
				$response = array("status_code" => 0,"message" => 'ok',"entity" =>$listuser);
			}
			else {
				$response = array("status_code" => -1,"message" => $err,"entity" =>'');
			}
			echo json_encode($response);

		}
	}


	public function unretweet(){
		//$this->autoRender = true;
		$dataSource = $this->Tweet->getDataSource();
		$err = null;
		$response;
		if($this->request->is('post')){
			if(empty($this->request->data['tweet_id'])){
				$err .= "not found tweet_id param";

			}
			if(!isset($this->request->data['user_id'])){
				$err .= "not found user_id param";
					
			}

			//debug($this->request->data);
			//debug(empty($err));
			if(empty($err)){
					
				$userId=$this->request->data['user_id'];
				$tweetId = $this->request->data['tweet_id'];
				$retweet = $this->Tweet->find('first',
						array('conditions'=>array('Tweet.user_id'=>$userId,'Tweet.parent_id'=>$tweetId,'Tweet.type'=>'3')));

				//neu tweet nay da duoc use dang dang nhap retweet
				if($retweet!=null){
				 //xoa du lieu trong timeline, favorite,tweet
					$this->delatweet($retweet['Tweet']['id']);
					$response = array("status_code" => 0,"message" => "UnReTweet ok!!!","entity" => array());
				}
				else{

					$response = array("status_code" => -1,"message" => "UnReTweet false, this tweet isnt retweeted by you !!!","entity" =>array());
				}

			}
			else {
				$response = array("status_code" => -1,"message" => $err,"entity" =>'');
			}
			echo json_encode($response);

		}

	}


	public function delete(){
		//$this->autoRender = true;
		$dataSource = $this->Tweet->getDataSource();
		$err = null;
		$response;
		if($this->request->is('post')){
			if(empty($this->request->data['tweet_id'])){
				$err .= "not found tweet_id param";

			}
			if(!isset($this->request->data['user_id'])){
				$err .= "not found user_id param";
					
			}
			/*
			 if(!isset($this->request->data['image_url'])){
			$err .= "not found image_id param";

			}
			if(empty($this->request->data['parent_id'])){
			$err .= "not found parent_id param";

			}
			if(empty($this->request->data['type'])){
			$err .= "not found type param";

			}
			*/
			//debug($this->request->data);
			//debug(empty($err));
			if(empty($err)){
				$userId=$this->request->data['user_id'];
				$tweetId = $this->request->data['tweet_id'];
				$tweet = $this->Tweet->find('first',
						array('conditions'=>array('Tweet.user_id'=>$userId,'Tweet.id'=>$tweetId),'recursive'=>-1));

				//neu tweet nay thuoc ve use dang dang nhap
				if($tweet!=null){
					//xoa du lieu trong timeline, favorite,tweet
					//find all reweet of this tweet

					$retweetList = $this->Tweet->find('list',array('conditions'=>array('Tweet.parent_id'=>$tweetId,'Tweet.type'=>'3'),'recursive'=>-1));
					//delete all retweet of this tweet
					//debug($retweetList);
					foreach ($retweetList as $key =>$value ){
						//debug( $value);
						$this->delatweet($value);


					}
					//del this tweet
					$this->delatweet($tweetId);
					$response = array("status_code" => 0,"message" => "delete ok!!!","entity" => array());
				}
				else{

					$response = array("status_code" => -1,"message" => "delete false, this tweet not belongs to by you !!!","entity" =>array());
				}

			}
			else {
				$response = array("status_code" => -1,"message" => $err,"entity" =>'');
			}
			echo json_encode($response);

		}




	}

	public function tweet(){
		//$this->autoRender = true;
		if($this->request->is("post")){
			$userid = $this->request->data['Tweet']['user_id'];
			$content = $this->request->data['Tweet']['content'];
			$allTweet = array();
			for ($i = 0;$i < 1000;$i++){
				$data = array("user_id" => $userid,"tweet_id" =>$content.$i);
				array_push($allTweet, $data);

			}
			$this->Timeline->saveMany($allTweet);
		}
	}

	private function delatweet($tweetId) {
		$this->Timeline->deleteAll(array('Timeline.tweet_id'=>$tweetId),false);
		$this->Favorite->deleteAll(array('Favorite.tweet_id'=>$tweetId),false);
		$this->Tweet->deleteAll(array('Tweet.id'=>$tweetId),false);
		$this->Place->deleteAll(array('Place.tweet_id'=>$tweetId),false);
	}

	private function insertTweet($userId,$content,$imageUrl,$parentId,$type,$placeId){
		$dataSource = $this->Tweet->getDataSource();
		//$dataSource->begin();
		$data = array('Tweet'=>array(
				'content'=>$content,
				'image_url'=>$imageUrl,
				'status'=>'',
				'user_id'=>$userId,
				'parent_id'=>$parentId,
				'type'=>$type));
		if($this->Tweet->save($data)){
			//save all mention
			$part = "/(?:\s|^)(?:@)[A-Za-z0-9_-]{1,15}/";

			//print $content;
			preg_match_all($part, $content, $matches);
			//debug($matches);
			$mentionList= array();
			foreach ($matches[0] as $key =>$value ){
				$value = trim($value,' @');
				//print $value;
				$username=$this->User->find( 'first', array('conditions' => (array('username'=>$value)), 'recursive' => -1));
				if($username!=null){
					//them du lieu vaobang mention
					//debug($username);
					$mention = array('Mention' =>array(
							'user_id' =>$username['User']['id'],
							'tweet_id' => $this->Tweet->id));
					array_push($mentionList,$mention);


				}
			}
			if($this->Mention->saveMany($mentionList)){
				//print 'Mention ok';

			}
			else{
				//print "cant mention";
			}
			//insert place
			$place = array('Place'=>array('tweet_id'=>$this->Tweet->id,'place_id'=>$placeId));
			if($this->Place->save($place)){
					
			}else{
				print 'cannot insert place';
			}
			$this->Session->setFlash("This tweet was saved success");
			//$owner=$this->User->find( 'first', array('conditions' => (array('id'=>$userId)), 'recursive' => -1));
			//$this->Follow->unbindModel(array('belongsTo'=>array('FollowerUser')));
			//$follower = $this->Follow->find('all',array('fields'=>array('FollowingUser.*'),'conditions'=>array('Follow.following_id'=>$userId),'recursive'=>2));
			//debug($follower);
			//debug($owner);
			$tweetId=$this->Tweet->id;
			$query ='insert DELAYED into timelines (user_id,tweet_id,followed_id)
			select follower_id,' .$tweetId.' , '.$userId.' from follows where following_id = '.$userId;


			$query2= 'insert DELAYED into timelines (user_id,tweet_id,followed_id)'.
					'Values ('.$userId.' , '.$tweetId.' ,'.$userId.')';
			$dataSource->query($query2);
			$dataSource->query($query);
			//$this->notification($tweetId);
			//$this->requestAction()
			//$this->JobStartAsync('faketwitter.com','/Tweets/notification.php?tweet_id='.$tweetId);
			//$dataSource->commit();
			return 0;



		}else{
			//co loi rollback du lieu
			//$dataSource->rollback();
			//$this->Session->setFlash("Unable to save post");
			//$response = array("status_code" => -1,"message" => "Tweet false !!!","entity" =>'');
			return -1;
		}
			
	}
	private function insertReTweet($userId,$content,$imageUrl,$parentId,$type){
		$dataSource = $this->Tweet->getDataSource();
		//$dataSource->begin();
		$data = array('Tweet'=>array(
				'content'=>$content,
				'image_url'=>$imageUrl,
				'status'=>'',
				'user_id'=>$userId,
				'parent_id'=>$parentId,
				'type'=>$type));
		$parentTweet = $this->Tweet->find('first',array('conditions'=>array('Tweet.id'=>$parentId),'recursive'=>-1));
		//debug($parentTweet);
		if($parentTweet!=null&&$this->Tweet->save($data)){
			$tweetId =$this->Tweet->id;
			$this->Session->setFlash("This tweet was saved success");
			//$parentTweet = $this->Tweet->find('first',array('conditions'=>array('Tweet.id'=>$tweetId),'recursive'=>-1));
			//$parentUserTweet = $parentTweet['Tweet']['user_id'];
			//debug($parentUserTweet);
			$parentUser=$parentTweet['Tweet']['user_id'];
			$query ="insert DELAYED into timelines (user_id,tweet_id,followed_id)
			Select Follow.follower_id ,$tweetId ,$userId
			From follows as Follow
			Left join follows as Followed
			on   Followed.follower_id = Follow.follower_id and Followed.following_id = $parentUser
			Where  Follow.follower_id <> $parentUser and Follow.following_id =$userId and isnull(Followed.following_id)
			";
			$dataSource->query($query);
			//$dataSource->commit();
			return 0;


		}else{
			//co loi rollback du lieu
			//$dataSource->rollback();
			//$this->Session->setFlash("Unable to save post");
			//$response = array("status_code" => -1,"message" => "Tweet false !!!","entity" =>'');
			return -1;
		}

	}
	public function get_parent_of_replytweet(){
		$err = null;
		$response;
		if($this->request->is('post')){
			if(empty($this->request->data['tweet_id'])){
				$err .= "not found tweet_id param";
					
			}

			//debug($this->request->data);
			//debug(empty($err));
			if(empty($err)){
					
				$tweetId = $this->request->data['tweet_id'];
				$query =  'select User.id ,User.avatar,User.username,User.email,User.screen_name,User.created
				, Tweet.*,(TIMEDIFF(UTC_TIMESTAMP(),Tweet.created)) as leftTime, not isnull(Favorite.id) as favorite ,(Tweet.type=3) as retweetedbyme,Retweet.*,ParentUser.*
				from tweets as Tweet
				inner join users as User
				on Tweet.id = '.$tweetId.' and
				User.id = Tweet.user_id
				left join favorites as Favorite
				on Tweet.id = Favorite.tweet_id and Favorite.user_id = Tweet.user_id
				left join tweets as Retweet
				on Tweet.type = 3 and Tweet.parent_id = Retweet.id
				left join users as ParentUser
				on Tweet.type = 3 and Retweet.user_id = ParentUser.id
				order by Tweet.id DESC
				Limit 1';
				$tweet = $this->Tweet->getDataSource()->query($query);
				//debug($tweet);
				// 				$this->Tweet->unbindModel(array('hasMany'=>array('Timeline','Mention','Favorite'),'hasOne'=>array('Place')));
				// 				$tweet = $this->Tweet->find('first',
				// 						array('conditions'=>array('Tweet.id'=>$tweetId)));
				// 				//debug($tweet);
				$listparent=array();
				while($tweet[0]['Tweet']['parent_id']>=0&&$tweet[0]['Tweet']['type']==2){
					$tweetId=$tweet[0]['Tweet']['parent_id'];
					$query =  'select User.id ,User.avatar,User.username,User.email,User.screen_name,User.created
					, Tweet.*,(TIMEDIFF(UTC_TIMESTAMP(),Tweet.created)) as leftTime, not isnull(Favorite.id) as favorite ,(Tweet.type=3) as retweetedbyme,Retweet.*,ParentUser.*
					from tweets as Tweet
					inner join users as User
					on Tweet.id = '.$tweetId.' and
					User.id = Tweet.user_id
					left join favorites as Favorite
					on Tweet.id = Favorite.tweet_id and Favorite.user_id = Tweet.user_id
					left join tweets as Retweet
					on Tweet.type = 3 and Tweet.parent_id = Retweet.id
					left join users as ParentUser
					on Tweet.type = 3 and Retweet.user_id = ParentUser.id
					order by Tweet.id DESC
					Limit 1';
					$tweet = $this->Tweet->getDataSource()->query($query);
					// 							array('conditions'=>array('Tweet.id'=>$tweet['Tweet']['parent_id']),
					// 									'fields'=>array('Tweet.*','User.*','(TIMEDIFF(UTC_TIMESTAMP(),Tweet.created)) as leftTime ')));

					if($tweet!=null){
						// 						//debug($tweet);
						// 						//add favorite neu user hien tai thich tweet nay


						//debug($tweet[0]);
						//die;
						//debug($query);
						array_push($listparent, $tweet[0]);
						// 						//debug($listparent);
						// 						//die();
					}
					else {
						break;
					}

				}
				//debug($listparent);
				$response = array("status_code" => 0,"message" =>'0k',"entity" =>$listparent);
			}
			else {
				$response = array("status_code" => -1,"message" => $err,"entity" =>'');
			}
			echo json_encode($response);
		}
	}

	public function get_replies(){
		$err = null;
		$response;
		if($this->request->is('post')){
			if(empty($this->request->data['tweet_id'])){
				$err .= "not found tweet_id param";

			}

			//debug($this->request->data);
			//debug(empty($err));
			if(empty($err)){
				$tweetId = $this->request->data['tweet_id'];
				$query =  'select User.id ,User.avatar,User.username,User.email,User.screen_name,User.created
				, Tweet.*,(TIMEDIFF(UTC_TIMESTAMP(),Tweet.created)) as leftTime, not isnull(Favorite.id) as favorite ,(Tweet.type=3) as retweetedbyme,Retweet.*,ParentUser.*
				from tweets as Tweet
				inner join users as User
				on Tweet.parent_id = '.$tweetId.' and
				Tweet.type= 2 and
				User.id = Tweet.user_id
				left join favorites as Favorite
				on Tweet.id = Favorite.tweet_id and Favorite.user_id = Tweet.user_id
				left join tweets as Retweet
				on Tweet.type = 3 and Tweet.parent_id = Retweet.id
				left join users as ParentUser
				on Tweet.type = 3 and Retweet.user_id = ParentUser.id
				order by Tweet.id DESC
				';

				//debug($tweetId);
				$tweet =$this->Timeline->getDataSource()->query($query);
				//debug($tweet);
				$response = array("status_code" => 0,"message" =>'0k',"entity" =>$tweet);
			}
			else {
				$response = array("status_code" => -1,"message" => $err,"entity" =>'');
			}
			echo json_encode($response);
		}
			
	}

	public function get_retweet_count(){
		$err = null;
		$response;
		if($this->request->is('post')){
			if(empty($this->request->data['tweet_id'])){
				$err .= "not found tweet_id param";

			}

			//debug($this->request->data);
			//debug(empty($err));
			if(empty($err)){

				$tweetId = $this->request->data['tweet_id'];
					
				$count = $this->Tweet->find('count',
						array('conditions'=>array('Tweet.parent_id'=>$tweetId,'Tweet.type'=>3),'recursive'=>-1));
				//debug($tweet);
				//debug($count);
				$response = array("status_code" => 0,"message" =>'0k',"entity" =>$count);
			}
			else {
				$response = array("status_code" => -1,"message" => $err,"entity" =>'');
			}
			echo json_encode($response);
		}

	}

	public function get_tweet_count(){
		$err = null;
		$response;
		if($this->request->is('post')){
			if(empty($this->request->data['userid'])){
				$err .= "not found userid param";

			}

			//debug($this->request->data);
			//debug(empty($err));
			if(empty($err)){

				$userId = $this->request->data['userid'];

				$count = $this->Tweet->find('count',
						array('conditions'=>array('Tweet.user_id'=>$userId)));
				//debug($tweet);
				//debug($count);
				$response = array("status_code" => 0,"message" =>'0k',"entity" =>$count);
			}
			else {
				$response = array("status_code" => -1,"message" => $err,"entity" =>'');
			}
			echo json_encode($response);
		}

	}

	public  function notification($tweetId){
		
		//$tweetId = $_GET['tweet_id'];
		//$debug($this->request->data);
		$tweet =$this->Tweet->find('first',array('conditions'=>array('id'=>$tweetId),'recursive'=>-1));
		$owner = $this->User->find('first',array('conditions'=>array('id'=>$tweet['Tweet']['user_id']),'recursive'=>-1));
		debug($tweet);
		debug ($owner);
		$follower = $this->Follow->find('all',array('fields'=>array('FollowingUser.*'),'conditions'=>array('Follow.following_id'=>$owner['User']['id'],'FollowingUser.reg_id <>'=>'null'),'recursive'=>2));
		//debug($follower);
		//debug($owner);
			
		//debug($follower);
		
		foreach ($follower as $key => $value){
			//echo $key .'   and   '. $value;
			//$timeline = array('user_id'=>$value['FollowingUser']['id'],'tweet_id'=>$this->Tweet->id,'followed_id'=>$userId);
			//array_push($timelineList, $timeline);
			$this->pushnofifycation($value['FollowingUser'],$tweet['Tweet'],$owner['User']);

		}
	}
	private function pushnofifycation($user,$tweet,$owner){
		$url = 'https://android.googleapis.com/gcm/send';
		$serverApiKey = "AIzaSyAmubg2LaSEzHQmKhYcboKKBzYX9J1rtGM";
		$reg =$user['reg_id']; //"APA91bHWfohJSW3tIKT02dBmdSihP6Fx1UwlwRh18ZCG66wMLtwmdWAscTSzaqCu7jFtGCipzPCkEZrYLLDnp3lqQYIyZqrqueDU43wraD2Kg1IwlBLBykg4hm2iUXuxm00tuUb5PIn7";

		$headers = array(
				'Content-Type:application/json',
				'Authorization:key=' . $serverApiKey
		);
		$sentTweet['Tweet']= $tweet;
		$sentTweet['User']=$owner;
		$sentTweet['0']['favorite']='0';
		$sentTweet['ReTweet']=array();
		$sentTweet['0']['retweetedbyme']='0';
		//debug($sentTweet);
		//debug($owner);
		$data = array(
				'registration_ids' => array($reg)
				, 'data' => array(
						'type' => 'New',
						'title' => 'FakeTwitter',
						'msg' => $owner['username'].' has just tweeted: '.$tweet['content'],
						'url' => 'http://faketwitter.com',
						'tweet'=>$sentTweet
				)
		);

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		if ($headers)
			curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

		$response = curl_exec($ch);

		curl_close($ch);
		//	print ($response);
	}

	private function JobStartAsync($server, $url, $port=80,$conn_timeout=30, $rw_timeout=86400)
	{   
		$errno = '';
		$errstr = '';

		set_time_limit(0);

		$fp = fsockopen($server, $port, $errno, $errstr, $conn_timeout);
		if (!$fp) {
			echo "$errstr ($errno)<br />\n";
			return false;
		}
		$out = "GET $url HTTP/1.1\r\n";
		$out .= "Host: $server\r\n";
		$out .= "Connection: Close\r\n\r\n";

		//stream_set_blocking($fp, false);
		//stream_set_timeout($fp, $rw_timeout);
		//fwrite($fp, $out);

		return $fp;
	}

}